package com.sky.aspect;


import com.sky.annotation.AutoClean;
import com.sky.annotation.AutoFill;
import com.sky.dto.DishDTO;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Set;

@Aspect
@Slf4j
@Component
public class AutoCleanAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("execution(* com.sky.controller.admin.DishController.*(..)) && @annotation(com.sky.annotation.AutoClean))")
    public void AutoCleanPointCut(){}


    @Before("AutoCleanPointCut()")
    public void autoClean(JoinPoint joinPoint){
        log.info("检测到删除与修改操作，开始进行Redis缓存清理...");
        MethodSignature methodsignature = (MethodSignature) joinPoint.getSignature();
        AutoClean autoClean = methodsignature.getMethod().getAnnotation(AutoClean.class);
        OperationType type = autoClean.value();


        //由于新增操作默认为停售状态，所以只需对删改操作进行缓存清理即可
        //如果是新增操作
        /*if(type == OperationType.INSERT){
            Object[] args = joinPoint.getArgs();
            DishDTO dishDTO = (DishDTO) args[0];
            String key = "dish_" + dishDTO.getCategoryId();
            redisTemplate.delete(key);
            return;
        }*/

        //删改操作时，将所有缓存都清除
        String key = "dish_*";
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }
}
